package server;

import db.DruidDBPool;
import db.JedisDBPool;
import utils.CommonUtils;

import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;

public class Main {

    public static void main(String[] args) throws Exception{
        Properties properties = CommonUtils.readPropertiesFile("server_address.properties");
        int serverNumber = 1;     //服务器编号
        int serverPort = 10001;   //服务器端口
        boolean isEnable = false;
        for (;serverNumber <= properties.size();serverNumber++) {
            String serverName = "server" + serverNumber;
            serverPort = Integer.valueOf(properties.getProperty(serverName));
            if (!isPortUsing("127.0.0.1", serverPort)) {
                isEnable = true;
                break;
            }
        }
        if (!isEnable) {
            System.out.println("所有服务器都已启动完毕！");
            return;
        }
        //启动服务器
        System.out.println(">>>>>>>>>>>>>>>>>" + serverNumber + "号服务器（127.0.0.1:" + serverPort + "）启动中......");
        startServer(serverNumber, serverPort);
    }

    /**
     * 启动对应服务器（即开始监听指定端口）
     * @param port 端口号
     */
    private static void startServer(int serverNumber, int port) {
        //连接redis
        JedisDBPool.initConnection();
        //连接数据库
        DruidDBPool.initConnection();
        //启动端口监听
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>" + serverNumber + "号服务器启动完成");
        Server server = new Server();
        server.listen(port);
    }

    /**
     * 检测服务器是否已经启动（即检测端口是否已被占用）
     */
    public static boolean isPortUsing(String host, int port){
        boolean flag = false;
        try {
            InetAddress Address = InetAddress.getByName(host);
            //端口与Socket是一一对应的关系，一个Socket只能占用一个端口,因此可以通过这种方式检测
            //如果能与该端口建立socket连接，说明该端口已被使用
            Socket socket = new Socket(Address, port);
            flag = true;
            socket.close();
        } catch (Exception ignored) {
        }
        return flag;
    }
}
